"""
监控面板 API 路由
"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import Optional, List, Dict, Any
import json

from database import get_db
from services.monitoring_service import MonitoringService
from models.workflow_instance import WorkflowInstance

router = APIRouter(
    prefix="/api/monitoring",
    tags=["monitoring"]
)


@router.get("/statistics", summary="获取监控统计数据")
def get_monitoring_statistics(
    days: int = Query(7, ge=1, le=30, description="统计天数"),
    db: Session = Depends(get_db)
):
    """
    获取监控统计数据

    - **running_workflows**: 正在运行的工作流数量
    - **today_success**: 今日成功数量
    - **today_failed**: 今日失败数量
    - **success_rate**: 整体成功率
    - **trend**: 最近N天的趋势数据
    """
    statistics = MonitoringService.get_statistics(db, days)
    return statistics


@router.get("/recent-instances", summary="获取最近的工作流实例")
def get_recent_instances(
    limit: int = Query(20, ge=1, le=100, description="返回数量"),
    status: Optional[str] = Query(None, description="状态筛选"),
    db: Session = Depends(get_db)
):
    """
    获取最近的工作流实例

    可选按状态筛选
    """
    instances = MonitoringService.get_recent_instances(db, limit, status)

    # 转换为响应格式
    result = []
    for instance in instances:
        result.append({
            "id": instance.id,
            "workflow_id": instance.workflow_id,
            "instance_name": instance.instance_name,
            "status": instance.status,
            "trigger_type": instance.trigger_type,
            "created_at": instance.created_at.isoformat() if instance.created_at else None,
            "started_at": instance.started_at.isoformat() if instance.started_at else None,
            "finished_at": instance.finished_at.isoformat() if instance.finished_at else None,
            "duration": instance.duration,
            "current_node_id": instance.current_node_id
        })

    return {
        "total": len(result),
        "items": result
    }


@router.get("/status-distribution", summary="获取工作流状态分布")
def get_status_distribution(
    db: Session = Depends(get_db)
):
    """
    获取工作流状态分布统计

    返回各状态的数量
    """
    distribution = MonitoringService.get_workflow_status_distribution(db)
    return distribution


@router.get("/duration-statistics", summary="获取执行时长统计")
def get_duration_statistics(
    db: Session = Depends(get_db)
):
    """
    获取平均执行时长统计

    - **average_duration**: 平均时长（秒）
    - **min_duration**: 最小时长（秒）
    - **max_duration**: 最大时长（秒）
    - **total_count**: 统计样本数
    """
    stats = MonitoringService.get_average_duration(db)
    return stats


@router.get("/top-workflows", summary="获取执行次数最多的工作流")
def get_top_workflows(
    limit: int = Query(10, ge=1, le=50, description="返回数量"),
    db: Session = Depends(get_db)
):
    """
    获取执行次数最多的工作流

    返回工作流ID、执行次数、成功次数、成功率
    """
    top_workflows = MonitoringService.get_top_workflows(db, limit)
    return {
        "items": top_workflows
    }


@router.get("/realtime-status", summary="获取实时状态")
def get_realtime_status(
    db: Session = Depends(get_db)
):
    """
    获取实时状态概览

    用于监控面板的实时刷新
    """
    # 获取各状态的数量
    running_count = db.query(WorkflowInstance).filter(
        WorkflowInstance.status == '运行中'
    ).count()

    waiting_count = db.query(WorkflowInstance).filter(
        WorkflowInstance.status == '等待中'
    ).count()

    paused_count = db.query(WorkflowInstance).filter(
        WorkflowInstance.status.in_(['暂停中', '已暂停'])
    ).count()

    # 获取正在运行的实例列表
    running_instances = db.query(WorkflowInstance).filter(
        WorkflowInstance.status.in_(['运行中', '等待中'])
    ).order_by(WorkflowInstance.started_at.desc()).limit(10).all()

    running_list = []
    for instance in running_instances:
        running_list.append({
            "id": instance.id,
            "instance_name": instance.instance_name,
            "status": instance.status,
            "current_node_id": instance.current_node_id,
            "started_at": instance.started_at.isoformat() if instance.started_at else None
        })

    return {
        "running_count": running_count,
        "waiting_count": waiting_count,
        "paused_count": paused_count,
        "running_instances": running_list,
        "timestamp": json.dumps({"time": "now"})  # 时间戳用于客户端刷新
    }
